using AutoMapper;
using MediatR;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure.BaseRepository;
using System;

namespace S.M.SmartMedical.API.Write.Application.Handler
{
    /// <summary>
    /// 创建医院命令处理程序
    /// 处理医院创建逻辑
    /// </summary>
    public class CreateHospitalHandler : IRequestHandler<CreateHospitalCommand, APIResult<HospitalDto>>
    {
        private readonly IRepository<Hospital> _hospitalRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateHospitalHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public CreateHospitalHandler(
            IRepository<Hospital> hospitalRepository,
            IMapper mapper,
            ILogger<CreateHospitalHandler> logger)
        {
            _hospitalRepository = hospitalRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理创建医院请求
        /// </summary>
        public async Task<APIResult<HospitalDto>> Handle(CreateHospitalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始创建医院：{@Request}", request);

                // 创建医院实体
                var hospital = new Hospital
                {
                    Name = request.Name,
                    ImageUrl = request.ImageUrl,
                    Level = request.Level,
                    Type = request.Type,
                    Address = request.Address,
                    Phone = request.Phone,
                    Description = request.Description,
                    IsEnabled = request.IsEnabled,
                    Uploader = request.Uploader,
                    UploadTime = DateTime.Now,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };

                // 保存到数据库
                var result = await _hospitalRepository.AddAsync(hospital);
                if (result <= 0)
                {
                    _logger.LogError("创建医院失败，数据库保存失败");
                    return new APIResult<HospitalDto>
                    {
                        Code = APIEnum.Fail,
                        Message = "创建医院失败"
                    };
                }

                // 映射到DTO并返回
                var hospitalDto = _mapper.Map<HospitalDto>(hospital);
                hospitalDto.Id = result; // 设置返回的ID

                _logger.LogInformation("医院创建成功，ID：{Id}", result);

                return new APIResult<HospitalDto>
                {
                    Code = APIEnum.OK,
                    Message = "医院创建成功",
                    Data = hospitalDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建医院时发生错误");
                return new APIResult<HospitalDto>
                {
                    Code = APIEnum.Fail,
                    Message = "创建失败：" + ex.Message
                };
            }
        }
    }
}